import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, InputNumber, DatePicker, message, Popconfirm, Select, Upload, Statistic, Row, Col, Tag, Progress, Badge } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, SyncOutlined, EyeOutlined, BarChartOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;

const DouyinGroup = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [douyinConfigs, setDouyinConfigs] = useState([]);
  const [statistics, setStatistics] = useState({
    total: 0,
    active: 0,
    inactive: 0,
    totalSales: 0,
  });

  // 获取抖音配置列表
  const fetchDouyinConfigs = async () => {
    try {
      const response = await request('/api/v1/douyin', {
        method: 'GET',
        params: {
          page: 1,
          pageSize: 100,
        },
      });
      if (response.code === 200) {
        setDouyinConfigs(response.data.list);
      }
    } catch (error) {
      message.error('获取抖音配置列表失败');
    }
  };

  // 获取抖音团购活动列表
  const fetchList = async (page = current, size = pageSize) => {
    setLoading(true);
    try {
      const response = await request('/api/v1/douyin/group', {
        method: 'GET',
        params: {
          page,
          pageSize: size,
        },
      });
      if (response.code === 200) {
        setData(response.data.list);
        setTotal(response.data.total);
        
        // 计算统计数据
        const stats = {
          total: response.data.total,
          active: response.data.list.filter(item => item.status === 1).length,
          inactive: response.data.list.filter(item => item.status === 0).length,
          totalSales: response.data.list.reduce((sum, item) => sum + (item.sold_count || 0), 0),
        };
        setStatistics(stats);
      } else {
        message.error(response.msg || '获取抖音团购活动列表失败');
      }
    } catch (error) {
      message.error('获取抖音团购活动列表失败');
    }
    setLoading(false);
  };

  // 初始加载
  useEffect(() => {
    fetchDouyinConfigs();
    fetchList();
  }, []);

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setCurrent(pagination.current);
    setPageSize(pagination.pageSize);
    fetchList(pagination.current, pagination.pageSize);
  };

  // 打开添加/编辑模态框
  const showModal = (record = null) => {
    setEditingId(record ? record.id : null);
    setModalTitle(record ? '编辑抖音团购活动' : '添加抖音团购活动');
    form.resetFields();
    if (record) {
      // 转换时间戳为moment对象
      const values = {
        ...record,
        timeRange: [moment(record.start_time), moment(record.end_time)],
      };
      form.setFieldsValue(values);
    }
    setModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const { timeRange, ...restValues } = values;
      
      // 转换时间范围为时间戳
      const submitData = {
        ...restValues,
        start_time: timeRange[0].valueOf(),
        end_time: timeRange[1].valueOf(),
      };
      
      const url = editingId ? `/api/v1/douyin/group/${editingId}` : '/api/v1/douyin/group';
      const method = editingId ? 'PUT' : 'POST';
      
      const response = await request(url, {
        method,
        data: submitData,
      });
      
      if (response.code === 200) {
        message.success(editingId ? '更新成功' : '添加成功');
        setModalVisible(false);
        fetchList();
      } else {
        message.error(response.msg || (editingId ? '更新失败' : '添加失败'));
      }
    } catch (error) {
      console.error('表单提交错误:', error);
    }
  };

  // 删除抖音团购活动
  const handleDelete = async (id) => {
    try {
      const response = await request(`/api/v1/douyin/group/${id}`, {
        method: 'DELETE',
      });
      
      if (response.code === 200) {
        message.success('删除成功');
        fetchList();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 同步数据
  const handleSync = async (id) => {
    try {
      const response = await request(`/api/v1/douyin/group/${id}/sync`, {
        method: 'POST',
      });
      
      if (response.code === 200) {
        message.success('同步成功');
        fetchList();
      } else {
        message.error(response.msg || '同步失败');
      }
    } catch (error) {
      message.error('同步失败');
    }
  };

  // 查看活动详情
  const showGroupDetail = async (id) => {
    try {
      const response = await request(`/api/v1/douyin/group/${id}`, {
        method: 'GET',
      });
      
      if (response.code === 200) {
        Modal.info({
          title: '活动详情',
          width: 600,
          content: (
            <div style={{ marginTop: 16 }}>
              <p><strong>活动标题:</strong> {response.data.title}</p>
              <p><strong>原价:</strong> ¥{(response.data.original_price / 100).toFixed(2)}</p>
              <p><strong>团购价:</strong> ¥{(response.data.group_price / 100).toFixed(2)}</p>
              <p><strong>已售数量:</strong> {response.data.sold_count}</p>
              <p><strong>活动时间:</strong> {moment(response.data.start_time).format('YYYY-MM-DD HH:mm')} - {moment(response.data.end_time).format('YYYY-MM-DD HH:mm')}</p>
              <p><strong>状态:</strong> {response.data.status === 1 ? '启用' : '禁用'}</p>
            </div>
          ),
        });
      } else {
        message.error(response.msg || '获取详情失败');
      }
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '抖音团购Id',
      dataIndex: 'douyin_group_id',
      key: 'douyin_group_id',
      width: 120,
    },
    {
      title: '门店',
      dataIndex: 'store_name',
      key: 'store_name',
      width: 150,
      ellipsis: true,
    },
    {
      title: '活动标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
    },
    {
      title: '价格',
      key: 'price',
      width: 120,
      render: (_, record) => (
        <div>
          <div style={{ textDecoration: 'line-through', color: '#999' }}>
            ¥{(record.original_price / 100).toFixed(2)}
          </div>
          <div style={{ color: '#f5222d', fontWeight: 'bold' }}>
            ¥{(record.group_price / 100).toFixed(2)}
          </div>
        </div>
      ),
    },
    {
      title: '人数',
      key: 'people',
      width: 80,
      render: (_, record) => (
        <span>{record.min_count}-{record.max_count}人</span>
      ),
    },
    {
      title: '销售进度',
      key: 'progress',
      width: 120,
      render: (_, record) => {
        const sold = record.sold_count || 0;
        const max = record.max_count || 1;
        const percent = Math.min((sold / max) * 100, 100);
        return (
          <div>
            <Progress 
              percent={percent} 
              size="small" 
              format={() => `${sold}/${max}`}
            />
          </div>
        );
      },
    },
    {
      title: '活动时间',
      key: 'time',
      width: 200,
      render: (_, record) => {
        const now = moment();
        const start = moment(record.start_time);
        const end = moment(record.end_time);
        let status = '进行中';
        let color = 'green';
        
        if (now.isBefore(start)) {
          status = '未开始';
          color = 'blue';
        } else if (now.isAfter(end)) {
          status = '已结束';
          color = 'red';
        }
        
        return (
          <div>
            <div>{start.format('MM-DD')} - {end.format('MM-DD')}</div>
            <Tag color={color}>{status}</Tag>
          </div>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => (
        status === 1 ? 
          <Tag color="green" icon={<CheckCircleOutlined />}>启用</Tag> : 
          <Tag color="red" icon={<CloseCircleOutlined />}>禁用</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => showGroupDetail(record.id)}
            title="查看详情"
          />
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
            title="编辑"
          />
          <Button
            type="link"
            icon={<SyncOutlined />}
            onClick={() => handleSync(record.id)}
            title="同步数据"
          />
          <Popconfirm
            title="确定要删除这个活动吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />} title="删除" />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Statistic title="总活动数" value={statistics.total} prefix={<BarChartOutlined />} />
          </Col>
          <Col span={6}>
            <Statistic title="进行中" value={statistics.active} valueStyle={{ color: '#3f8600' }} />
          </Col>
          <Col span={6}>
            <Statistic title="已结束" value={statistics.inactive} valueStyle={{ color: '#cf1322' }} />
          </Col>
          <Col span={6}>
            <Statistic title="总销量" value={statistics.totalSales} suffix="单" />
          </Col>
        </Row>

        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => showModal()}
            >
              添加抖音团购活动
            </Button>
            <Button
              type="default"
              icon={<SyncOutlined />}
              onClick={() => fetchList()}
            >
              刷新数据
            </Button>
          </Space>
        </div>
        
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          onChange={handleTableChange}
        />
        
        <Modal
          title={modalTitle}
          visible={modalVisible}
          onOk={handleSubmit}
          onCancel={handleCancel}
          width={800}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{ 
              status: 1,
              timeRange: [moment(), moment().add(7, 'days')],
              min_count: 1,
              max_count: 1
            }}
          >
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
              <Form.Item
                name="douyin_id"
                label="抖音配置"
                rules={[{ required: true, message: '请选择抖音配置' }]}
              >
                <Select placeholder="请选择抖音配置">
                  {douyinConfigs.map(config => (
                    <Option key={config.id} value={config.id}>
                      {config.store_name} ({config.poi_id})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              
              <Form.Item
                name="store_id"
                label="门店ID"
                rules={[{ required: true, message: '请输入门店ID' }]}
              >
                <InputNumber style={{ width: '100%' }} min={1} />
              </Form.Item>
              
              <Form.Item
                name="store_name"
                label="门店名称"
                rules={[{ required: true, message: '请输入门店名称' }]}
              >
                <Input />
              </Form.Item>
              
              <Form.Item
                name="title"
                label="活动标题"
                rules={[
                  { required: true, message: '请输入活动标题' },
                  { max: 200, message: '标题不能超过200个字符' }
                ]}
              >
                <Input />
              </Form.Item>
              
              <Form.Item
                name="original_price"
                label="原价(元)"
                rules={[
                  { required: true, message: '请输入原价' },
                  { type: 'number', min: 0, message: '原价必须大于0' }
                ]}
              >
                <InputNumber 
                  style={{ width: '100%' }} 
                  min={0} 
                  step={0.01}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                  onChange={(value) => {
                    form.setFieldsValue({ original_price: Math.round(value * 100) });
                  }}
                />
              </Form.Item>
              
              <Form.Item
                name="group_price"
                label="团购价(元)"
                rules={[
                  { required: true, message: '请输入团购价' },
                  { type: 'number', min: 0, message: '团购价必须大于0' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('original_price') > value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('团购价必须小于原价'));
                    },
                  }),
                ]}
              >
                <InputNumber 
                  style={{ width: '100%' }} 
                  min={0} 
                  step={0.01}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                  onChange={(value) => {
                    form.setFieldsValue({ group_price: Math.round(value * 100) });
                  }}
                />
              </Form.Item>
              
              <Form.Item
                name="min_count"
                label="最小开团人数"
                rules={[
                  { required: true, message: '请输入最小开团人数' },
                  { type: 'number', min: 1, message: '最小开团人数必须大于0' }
                ]}
              >
                <InputNumber style={{ width: '100%' }} min={1} />
              </Form.Item>
              
              <Form.Item
                name="max_count"
                label="最大开团人数"
                rules={[
                  { required: true, message: '请输入最大开团人数' },
                  { type: 'number', min: 1, message: '最大开团人数必须大于0' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('min_count') <= value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('最大开团人数必须大于等于最小开团人数'));
                    },
                  }),
                ]}
              >
                <InputNumber style={{ width: '100%' }} min={1} />
              </Form.Item>
              
              <Form.Item
                name="timeRange"
                label="活动时间"
                rules={[{ required: true, message: '请选择活动时间' }]}
              >
                <RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  style={{ width: '100%' }}
                />
              </Form.Item>
              
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
              
              <Form.Item
                name="douyin_group_id"
                label="抖音团购ID"
                rules={[{ required: true, message: '请输入抖音团购ID' }]}
              >
                <Input />
              </Form.Item>
            </div>

            <Form.Item
              name="description"
              label="活动描述"
              rules={[{ required: true, message: '请输入活动描述' }]}
            >
              <TextArea rows={3} />
            </Form.Item>
            
            <Form.Item
              name="activity_rules"
              label="活动规则"
            >
              <TextArea rows={3} />
            </Form.Item>
            
            <Form.Item
              name="service_terms"
              label="服务条款"
            >
              <TextArea rows={3} />
            </Form.Item>
            
            <Form.Item
              name="images"
              label="团购图片"
              rules={[{ required: false, message: '请上传团购图片' }]}
            >
              <Upload
                listType="picture-card"
                maxCount={9}
                action="/api/v1/upload"
                beforeUpload={(file) => {
                  const isImage = file.type.startsWith('image/');
                  if (!isImage) {
                    message.error('只能上传图片文件！');
                  }
                  const isLt2M = file.size / 1024 / 1024 < 2;
                  if (!isLt2M) {
                    message.error('图片必须小于2MB！');
                  }
                  return isImage && isLt2M;
                }}
                onChange={({ fileList }) => {
                  form.setFieldsValue({
                    images: fileList.map(file => file.response?.url || file.url).filter(Boolean)
                  });
                }}
              >
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传</div>
                </div>
              </Upload>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default DouyinGroup;